from .models import Attractions
import pandas as pd
import plotly.express as px
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def attractions_list(request):
    # 获取所有城市，并去重
    cities = Attractions.objects.values_list('city_name', flat=True).distinct()
    cities = [city.strip() for city in cities if city.strip()]  # 清理城市名称
    cities = list(set(cities))  # 去重

    # 获取筛选条件
    selected_city = request.GET.get('city')
    selected_sight_level = request.GET.get('sight_level')
    selected_is_free = request.GET.get('is_free')

    # 查询景点数据
    attractions = Attractions.objects.all()
    # 应用筛选条件
    if selected_city:
        attractions = attractions.filter(city_name=selected_city)
    if selected_sight_level:
        attractions = attractions.filter(sight_level=selected_sight_level)
    if selected_is_free:
        # 直接使用前端传来的 'True' 或 'False' 进行筛选
        attractions = attractions.filter(is_free=selected_is_free)

    # 排序
    if selected_city:
        attractions = attractions.order_by('-heat_score')
    else:
        attractions = attractions.order_by('city_name', '-heat_score')

    # 分页
    paginator = Paginator(attractions, 10)
    page_number = request.GET.get('page')  # 从 URL 中获取页数参数

    # 处理无效的页数参数
    try:
        page_obj = paginator.page(page_number)
    except (EmptyPage, PageNotAnInteger):
        # 如果页数无效，默认跳转到第一页
        page_obj = paginator.page(1)

    # 传递给模板
    context = {
        'page_obj': page_obj,
        'cities': cities,
        'selected_city': selected_city,
        'selected_sight_level': selected_sight_level,
        'selected_is_free': selected_is_free
    }
    return render(request, 'trip/list.html', context)

def attraction_detail(request, attraction_id):
    # 获取景点详情
    attraction = get_object_or_404(
        Attractions,
        id=attraction_id
    )

    # 处理JSON字段
    import json
    try:
        attraction.tag_name_list = json.loads(attraction.tag_name_list) if attraction.tag_name_list else []
        attraction.sight_category_info = json.loads(
            attraction.sight_category_info) if attraction.sight_category_info else []
        attraction.preferential_policies_list = json.loads(
            attraction.preferential_policies_list) if attraction.preferential_policies_list else []
        attraction.service_facility_list = json.loads(
            attraction.service_facility_list) if attraction.service_facility_list else []
    except json.JSONDecodeError:
        # 处理JSON解析错误
        attraction.tag_name_list = []
        attraction.sight_category_info = []
        attraction.preferential_policies_list = []
        attraction.service_facility_list = []

    return render(request, 'trip/detail.html', {'attraction': attraction})

def five_a_scenic_spots_map(request):
    five_a_spots = Attractions.objects.filter(sight_level='5A')

    if not five_a_spots.exists():
        return HttpResponse("没有找到 5A 景点数据。")

    data = []
    for spot in five_a_spots:
        try:
            lat = float(spot.latitude) if spot.latitude else None
            lon = float(spot.longitude) if spot.longitude else None
        except (ValueError, TypeError):
            continue

        if lat and lon:
            data.append({
                'poi_name': spot.poi_name,
                'city_name': spot.city_name,
                'heat_score': spot.heat_score,
                'is_free': spot.is_free,
                'market_price': spot.market_price,
                'latitude': lat,  # 已经是浮点数
                'longitude': lon,  # 已经是浮点数
            })

    if not data:
        return HttpResponse("没有有效的经纬度数据。")

    fig = px.scatter_mapbox(
        pd.DataFrame(data),
        lat="latitude",
        lon="longitude",
        hover_name="poi_name",
        hover_data=["city_name", "heat_score", "is_free", "market_price"],
        color_discrete_sequence=["blue"],
        zoom=3
    )
    fig.update_layout(title='全国5A景点分布散点图')
    # 使用高德地图
    fig.update_layout(
        mapbox_style="white-bg",
        mapbox_layers=[{
            "below": 'traces',
            "sourcetype": "raster",
            "source": ["https://webst01.is.autonavi.com/appmaptile?style=7&x={x}&y={y}&z={z}"]
        }]
    )

    return HttpResponse(fig.to_html(full_html=False))


